home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Can't figure this out
- Date: 21 Jan 1996 12:33:19 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4dttcv$a6p@umbc9.umbc.edu>
- References: <31000091.3778302@news.panix.com>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Dan'l <dm@panix.com> wrote:
- |> I am learning C and I have not had any problems understanding most
- |> concepts I have learned so far. But to date I still can't figure out
- |> how the outcome of this program is 15. Somehow one of the B's ends up
- |> a three and the other B a 5, or am I so off base that I can't see
- |> what's really happening. Can someone please walk me through this
- |> one. Thanks Dan'l
- |>
- |> #define A 3
- |> #define B A + A
- |> #define C B * B
- |>
- |> main()
- |> {
- |> printf("%d", C);
- |> return 0;
- |> }
-
- Well the preprocessor is very good at what it does which is simple textual
- substitution. What actually gets compiled is probably:
-
- printf("%d", 3 + 3 * 3 + 3);
-
- We know that * is always done before + according to C's rules of precedence.
- So This is now 3 + 9 + 3. Now order doesn't matter (left to right if you
- really are) since everything is +. This evaluates to 15 which is what you
- got. The solution is to fix the #defines by adding explicit ()'s.
-
- #define A 3
- #define B ((A) + (A))
- #define C ((B) * (B))
-
- Actually you don't need quite this many, but it's a good habit to get
- into. For instance, if A was an expression like (1+2) instead of simply 3
- then you would need this many.
-
- Now the result should be 36.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-